#!/bin/sh

source ./env.sh

# upload file
# $1: apisever
# $2: uri
# $3: package_path
# $4: user_data
# $5: judge_resp
function upload() {
    apiserver=$1
    uri=$2
    package_path=$3
    user_data=$4
    judge_resp=$5
    
    url=`printf "${apiserver}${uri}"`
    kv=
    for((i=0;i<${#user_data[@]};i++))
    do
        item=${user_data[i]}
        kv=`printf "${kv} -F ${item}"`
    done

    echo "start request: curl -Lks -H "FORCE-UPLOAD: TRUE" -F file=@${package_path} ${kv} \"${url}\""
    ret=`curl -Lks -H "FORCE-UPLOAD: TRUE" -F file=@${package_path} ${kv} ${url}`
    echo "get response: ${ret}"

    if [ "$judge_resp" == "yes" ];then
        is_ok=`echo ${ret} | grep "upload succeed"`
        if [ "$is_ok" == "" ];then
            # err_msg=`getJsonValuesByAwk "${ret}" "message" "unknown error"`
            echo "[ERR] upload failed, error: $ret" >&2
            exit 400
        fi
    fi
}

# server=https://xxxxx:443
server=$HOSTS
upload_uri=`printf "/${PREFIX}cava3/upload?accessToken=${ACCESSTOKEN}"`
judge_ret=yes

# user_data=(productType=saas agentType=dev)
user_data=(data1=value1)

upload ${server} ${upload_uri} DeviceList_test.xls ${user_data} ${judge_ret}
